package com.qianfeng.dbsm.impl;

import com.qianfeng.dbsm.admin.entity.TbMember;
import com.qianfeng.dbsm.admin.service.SysRoleService;
import com.qianfeng.dbsm.admin.service.TbMemberService;
import com.qianfeng.dbsm.common.Contants;
import com.qianfeng.dbsm.common.PageInfo;
import com.qianfeng.dbsm.dao.TbOrderCommissionDao;
import com.qianfeng.dbsm.entity.TbOrderCommission;
import com.qianfeng.dbsm.entity.TbProductDistribution;
import com.qianfeng.dbsm.service.TbOrderCommissionService;
import com.qianfeng.dbsm.service.TbProductDistributionService;
import com.qianfeng.dbsm.vo.CommissionQueryParamVo;
import com.qianfeng.dbsm.vo.OrderDetailVo;
import com.qianfeng.dbsm.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * (TbOrderCommission)表服务实现类
 *
 * @author makejava
 * @since 2022-11-16 09:29:51
 */
@Service("tbOrderCommissionService")
public class TbOrderCommissionServiceImpl implements TbOrderCommissionService {
    @Autowired
    private TbOrderCommissionDao tbOrderCommissionDao;

    @Autowired
    private TbMemberService tbMemberService;

    @Autowired
    private TbProductDistributionService productDistributionService;

    @Autowired
    private SysRoleService sysRoleService;
    /**
     * 通过orderNumber查询数据
     *
     * @param commissionQueryParamVo 主键
     * @return 实例对象
     */
    @Override
    public List<TbOrderCommission> queryCommissionListByParam(CommissionQueryParamVo commissionQueryParamVo) {
        //处理分页参数
        PageInfo pageInfo = new PageInfo();
        if(commissionQueryParamVo.getPage() == null || "".equals(commissionQueryParamVo.getPage())){
            commissionQueryParamVo.setPage(pageInfo.getPage());
        }
        if(commissionQueryParamVo.getPageSize() ==null || "".equals(commissionQueryParamVo.getPageSize())){
            commissionQueryParamVo.setPageSize(pageInfo.getPageSize());
        }
        commissionQueryParamVo.setPage((commissionQueryParamVo.getPage()-1)* commissionQueryParamVo.getPageSize());
        return this.tbOrderCommissionDao.queryCommissionListByParam(commissionQueryParamVo);
    }

    /**
     * 根据订单对象新增分润信息数据
     *
     * @param orderVo 订单对象
     * @return 实例对象
     */
    @Override
    public int createCommissionData(OrderVo orderVo) {
        int  line = 0;
        try{
            //1.查找当前所属的经销商id  ->订单表
            Integer sellerId = orderVo.getSellerId();
            //2.找到经销商的所有上级(通过用户编号) 1级 2级 ->用户表
            List<Integer> threeLevelList = tbMemberService.bossMembersById(sellerId);
            Integer threeLevel = null;
            Integer twoLevel = null;
            Integer oneLevel = null;

            if(threeLevelList!=null && threeLevelList.size()>0){
                threeLevel = threeLevelList.get(0);
                //拿到了第三级供应商的 编号
                //3.找到当前商品经销商设置的分成比例(通过经销商编号，商品编号) -> 分润表
                line += this.insertCommission(threeLevel,orderVo.getOrderDetailVoList());
                //4.计算每级分销商分润比
                //5.存入 分润表
                List<Integer> twoLevelList = tbMemberService.bossMembersById(threeLevel);
                if(twoLevelList!=null && twoLevelList.size()>0){
                    twoLevel = twoLevelList.get(0);
                    line += this.insertCommission(twoLevel,orderVo.getOrderDetailVoList());
                    List<Integer> oneLevelList = tbMemberService.bossMembersById(twoLevel);
                    if(oneLevelList!=null && oneLevelList.size()>0){
                        oneLevel = oneLevelList.get(0);
                        line += this.insertCommission(oneLevel,orderVo.getOrderDetailVoList());
                    }
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        return line;
    }

    /**
     * 分润订单审核
     * @param orderNumber
     * @param auditStatus 审核通过的状态
     * @return
     */
    @Override
    public boolean auditCommission(String orderNumber, Integer auditStatus) {
        if(auditStatus == Contants.AUDIT_STATUS_NO_AUDIT || auditStatus == Contants.AUDIT_STATUS_AUDITED_PASS || auditStatus == Contants.AUDIT_STATUS_AUDITED_NO_PASS){
            try{
                List<TbOrderCommission> orderCommissionList = this.tbOrderCommissionDao.queryByOrderNumber(orderNumber);
                if(orderCommissionList==null || orderCommissionList.size()==0){
                    throw new RuntimeException("订单审核失败,当前订单不存在!!!");
                }
                TbOrderCommission tbOrderCommission = new TbOrderCommission();
                tbOrderCommission.setSettlementStatus(auditStatus);
                tbOrderCommission.setOrderNumber(orderNumber);
                tbOrderCommission.setCashierTime(new Date());
                int line = this.tbOrderCommissionDao.updateCommission(tbOrderCommission);
                return line == 0?false:true;
            }catch (Exception e){
                throw new RuntimeException("订单审核失败:" + e.getMessage() );
            }
        }else{
            throw new RuntimeException("订单审核失败,参数异常" );
        }
    }
    /**
     * 通过经销商编号 产品编号 生成 分润表信息
     * @param sellerId
     * @param orderDetailVoList
     * @return
     */
    private int insertCommission(Integer sellerId, List<OrderDetailVo> orderDetailVoList){

        try{
            orderDetailVoList.forEach(orderDetailVo -> {
                TbOrderCommission tbOrderCommission = new TbOrderCommission();
                tbOrderCommission.setOrderNumber(orderDetailVo.getOrderNumber());
                tbOrderCommission.setSettlementStatus(Contants.AUDIT_STATUS_NO_AUDIT);
                tbOrderCommission.setSellerUid(sellerId);
                // 通过商品编号 和 销售人员编号-> 商品分润情况表 查到 比例
                List<TbProductDistribution> tbProductDistributions = productDistributionService.queryByProductAndUser(Integer.valueOf(orderDetailVo.getProductId()), sellerId);
                if(tbProductDistributions!=null && tbProductDistributions.size() > 0){
                    //再通过比例 查找vo
                    TbProductDistribution tbProductDistribution = tbProductDistributions.get(0);
                    Double sharingPercent = tbProductDistribution.getSharingPercent();
                    if(sharingPercent==null){
                        throw new RuntimeException("数据异常，请联系管理员!!!");
                    }
                    double amount = orderDetailVo.getSumPrice() * sharingPercent;
                    tbOrderCommission.setCommissionAmount(amount);//计算好分成
                    tbOrderCommission.setSettlementTime(new Date());
                    //这里需要查询用户表 财务审核 人员 的 编号
                    //需要查询系统中所有财务审核人员清单 然后 在这里填充
                    Integer cashierId = getCashierIdByRandom();
                    tbOrderCommission.setCashierUid(cashierId);
                    int line = this.tbOrderCommissionDao.insert(tbOrderCommission);
                }
            });
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        return 1;
    }

    /**
     * 随机抽取一个审核人员
     * @return
     */
    public Integer getCashierIdByRandom(){
        List<TbMember> tbMemberList = sysRoleService.TbMemberByRoleId(Contants.AUDIT_ROLE_ID);
        if(tbMemberList!=null && tbMemberList.size()>0){
            if(tbMemberList.size()==1){
                return tbMemberList.get(0).getMemberId();
            }
            Random random = new Random();
            int randomNum =random.nextInt(tbMemberList.size());
            return  tbMemberList.get(randomNum).getMemberId();
        }
        throw new RuntimeException("获取审核人员清单失败！！！");
    }


}
